// 用于拼接字符串（自动插入换行）并替换到代码文件的类
function myString(dfText) {
  this.val = dfText || "";
  this.add = (text) => (this.val += (text || "") + "\r\n");
  this.writeTo = (strCode, tag) => {
    return strCode.replace(new RegExp(`\\$\\$${tag},?`, "g"), this.val.trimLeft());
  };
}

import { getFormComponents, getTableComponents } from "./getFormComponents";

function getShowTabs(data) {
  // 转化成显示数据
  const tabList = window.$deepClone(data);
  const pMap = {};
  tabList.forEach((tab) => {
    const componentList = [];
    tab.components.forEach((component) => {
      if (["card"].includes(component.type)) {
        if (!pMap[component.prop]) {
          pMap[component.prop] = [];
        }
        component.children = pMap[component.prop];
      }
      if (component.ptype == "card") {
        if (!pMap[component.pid]) {
          pMap[component.pid] = [];
        }
        pMap[component.pid].push(component);

        delete component.pid;
        delete component.ptype;
      } else {
        componentList.push(component);
      }
    });
    tab.components = componentList;
  });
  toFilterCard(tabList);
  return tabList;
}
function toFilterCard(tabList) {
  tabList.forEach((tab) => {
    const componentList = [];
    tab.components.forEach((component) => {
      if (["card"].includes(component.type)) {
        component.children = toFilterCardSub(component.children);
        if (component.children.length > 0) {
          componentList.push(component);
        }
      } else {
        componentList.push(component);
      }
    });
    tab.components = componentList;
  });
}
function toFilterCardSub(cardList) {
  const list = [];
  cardList.forEach((cardComponent) => {
    if (cardComponent.type != "card") {
      list.push(cardComponent);
    } else {
      cardComponent.children = toFilterCardSub(cardComponent.children);
      if (cardComponent.children.length > 0) {
        list.push(cardComponent);
      }
    }
  });
  return list;
}
function renderForm(
  list,
  tableMap,
  //dataItemMap,
  //dataSourceMap,
  dbTable,
  upCtrls,
  components,
  TEMPLATE,
  DATACOMPUTED,
  FORMDATA,
  TABLEDATA,
  TABLEMETHODS,
  RULES,
  RESETFORM,
  VALIDATEFORM,
  SETFORM,
  GETFORM
) {
  list.forEach((component) => {
    if (["gridtable"].includes(component.type)) {
      tableMap[component.table] = true;
      TABLEDATA.add(`            ${window.$lowerFirst(component.table)}_columns:[`);
      TABLEMETHODS.add(`        handle${window.$upFirst(component.table)}AddRow(){`);
      TABLEMETHODS.add(`            let point = {}`);

      TEMPLATE.add(`                                <el-col v-if="lr_formLookAuth('${component.prop}')" :span="24" >`);
      if (!window.$validatenull(component.label)) {
        TEMPLATE.add(`                                    <div class="l-title" >{{$t('${component.label}')}}</div>`);
      }
      TEMPLATE.add(`                                    <l-edit-table`);
      TEMPLATE.add(`                                        ref="${window.$lowerFirst(component.table)}_table"`);
      TEMPLATE.add(`                                        addBtnText="${component.addBtnText}"`);
      TEMPLATE.add(`                                        :isAddBtn="${component.isAddBtn}"`);
      TEMPLATE.add(`                                        :isRemoveBtn="${component.isRemoveBtn}"`);
      TEMPLATE.add(`                                        :isShowNum="${component.isShowNum}"`);

      TEMPLATE.add(`                                        :dataSource="${window.$lowerFirst(component.table)}_data"`);
      TEMPLATE.add(
        `                                        :columns="lr_formTableAuth('${window.$lowerFirst(
          component.table
        )}',${window.$lowerFirst(component.table)}_columns)"`
      );

      TEMPLATE.add(`                                        @addRow="handle${window.$upFirst(component.table)}AddRow"`);
      TEMPLATE.add(
        `                                        @deleteRow="handle${window.$upFirst(component.table)}DeleteRow"`
      );

      TEMPLATE.add(`                                        >`);

      component.children.forEach((col) => {
        let ponitStr = `                {id:'${component.table}_${col.field}',prop:'${window.$lowerFirst(
          col.field
        )}',label:'${col.label}'`;

        if (col.labelWidth) {
          ponitStr += `,width:${col.labelWidth}`;
        }
        if (col.required) {
          ponitStr += `,required:${col.required}`;
        }
        if (col.patterns && col.patterns.length > 0) {
          ponitStr += `,patterns:${JSON.stringify(col.patterns)}`;
        }
        ponitStr += `},`;
        TABLEDATA.add(ponitStr);

        if (["radio", "checkbox", "select", "selectMultiple", "treeselect", "layerselect"].includes(col.type)) {
          if (col.dataType == "3" && col.upCtrl) {
            TABLEMETHODS.add(
              `        ${window.$lowerFirst(component.table)}_${window.$lowerFirst(col.field)}Options(row){`
            );
            TABLEMETHODS.add(
              `            const data = this.lr_DataSource('${col.dataCode}',true,row.${window.$lowerFirst(
                components[col.upCtrl].field
              )},'${col.dataValueKey}')`
            );
            if (col.type == "treeselect") {
              TABLEMETHODS.add(
                `            return this.lr_DataSourceTree(data,'${col.dataIdKey}','${col.dataPIdKey}','${col.dataValueKey}','${col.dataLabelKey}')`
              );
            } else {
              TABLEMETHODS.add(
                `            return this.lr_DataSourceOptions(data,'${col.dataValueKey}','${col.dataLabelKey}')`
              );
            }
            TABLEMETHODS.add(`        },`);
          } else if (col.dataType == "4" && col.upCtrl) {
            TABLEMETHODS.add(
              `        ${window.$lowerFirst(component.table)}_${window.$lowerFirst(col.field)}Options(row){`
            );

            if (col.type == "layerselect") {
              TABLEMETHODS.add(`            return []`);
            } else {
              TABLEMETHODS.add(
                `            const data = this.lr_ApiDataSource('${col.apiCode}','${
                  col.apiUrl
                }',true,row.${window.$lowerFirst(components[col.upCtrl].field)},'${col.dataValueKey}')`
              );
              if (col.type == "treeselect") {
                TABLEMETHODS.add(
                  `            return this.lr_DataSourceTree(data,'${col.dataIdKey}','${col.dataPIdKey}','${col.dataValueKey}','${col.dataLabelKey}')`
                );
              } else {
                TABLEMETHODS.add(
                  `            return this.lr_DataSourceOptions(data,'${col.dataValueKey}','${col.dataLabelKey}')`
                );
              }
            }

            TABLEMETHODS.add(`        },`);
          } else {
            DATACOMPUTED.add(
              `        ${window.$lowerFirst(component.table)}_${window.$lowerFirst(col.field)}Options(){`
            );
            switch (col.dataType) {
              case "1":
                // 1.静态数据
                DATACOMPUTED.add(`            return ${JSON.stringify(col.options)}`);
                break;
              case "2":
                // 2.数据字典数据
                //dataItemMap[col.dataCode] = true;
                DATACOMPUTED.add(`            this.lr_loadDataItem('${col.dataCode}')`);
                if (col.type == "treeselect") {
                  DATACOMPUTED.add(`            return this.lr_dataItemTree(this.lr_dataItem['${col.dataCode}'])`);
                } else {
                  DATACOMPUTED.add(`            return this.lr_dataItemOptions(this.lr_dataItem['${col.dataCode}'])`);
                }
                break;
              case "3":
                // 3.数据源数据
                //dataSourceMap[col.dataCode] = true;

                DATACOMPUTED.add(`            const data = this.lr_DataSource('${col.dataCode}')`);

                if (col.type == "treeselect") {
                  DATACOMPUTED.add(
                    `            return this.lr_DataSourceTree(data,'${col.dataIdKey}','${col.dataPIdKey}','${col.dataValueKey}','${col.dataLabelKey}')`
                  );
                } else {
                  DATACOMPUTED.add(
                    `            return this.lr_DataSourceOptions(data,'${col.dataValueKey}','${col.dataLabelKey}')`
                  );
                }

                break;

              case "4":
                if (col.type == "layerselect") {
                  DATACOMPUTED.add(`            return []`);
                } else {
                  DATACOMPUTED.add(`            const data = this.lr_ApiDataSource('${col.apiCode}','${col.apiUrl}')`);
                  if (col.type == "treeselect") {
                    DATACOMPUTED.add(
                      `            return this.lr_DataSourceTree(data,'${col.dataIdKey}','${col.dataPIdKey}','${col.dataValueKey}','${col.dataLabelKey}')`
                    );
                  } else {
                    DATACOMPUTED.add(
                      `            return this.lr_DataSourceOptions(data,'${col.dataValueKey}','${col.dataLabelKey}')`
                    );
                  }
                }
            }
            DATACOMPUTED.add(`        },`);
          }
        }

        TEMPLATE.add(
          `                                        <template v-slot:${window.$lowerFirst(col.field)}="scope" >`
        );
        TEMPLATE.add(
          getTableComponents(
            col,
            window.$lowerFirst(col.field),
            "                                            ",
            component.table,
            upCtrls[col.prop]
          )
        );
        TEMPLATE.add(`                                        </template>`);

        if (["rate", "slider"].includes(component.type)) {
          TABLEMETHODS.add(`            point.${window.$lowerFirst(col.field)} = ${col.default || 0}`);
        } else {
          TABLEMETHODS.add(`            point.${window.$lowerFirst(col.field)} = "${col.default || ""}"`);
        }
      });

      TEMPLATE.add(`                                    </l-edit-table>`);
      TEMPLATE.add(`                                </el-col>`);

      TABLEDATA.add(`            ],`);
      TABLEDATA.add(`            ${window.$lowerFirst(component.table)}_data:[],`);

      RESETFORM.add(`            this.${window.$lowerFirst(component.table)}_data = []`);

      const table = dbTable.find((t) => t.name == component.table);
      SETFORM.add(
        `            this.${window.$lowerFirst(component.table)}_data = data.${window.$lowerFirst(table.className)}List`
      );
      GETFORM.add(
        `            formData.${window.$lowerFirst(table.className)}List = this.${window.$lowerFirst(
          component.table
        )}_data`
      );

      VALIDATEFORM.add(`            if(!this.$refs.${window.$lowerFirst(component.table)}_table.validate())`);
      VALIDATEFORM.add(`            {`);
      VALIDATEFORM.add(`                return false`);
      VALIDATEFORM.add(`            }`);

      TABLEMETHODS.add(`            this.${window.$lowerFirst(component.table)}_data.push(point)`);
      TABLEMETHODS.add(`        },`);

      TABLEMETHODS.add(`        handle${window.$upFirst(component.table)}DeleteRow(event){`);
      TABLEMETHODS.add(`            this.${window.$lowerFirst(component.table)}_data.splice(event.index,1)`);
      TABLEMETHODS.add(`        },`);
    } else if (["divider"].includes(component.type)) {
      TEMPLATE.add(
        `                                <el-col v-if="lr_formLookAuth('${component.prop}')"  :span="${component.span}" >`
      );
      TEMPLATE.add(
        `                                    <el-divider content-position="${component.contentPosition}">${component.html}</el-divider>`
      );
      TEMPLATE.add(`                                </el-col>`);
    } else if (["btn"].includes(component.type)) {
      TEMPLATE.add(
        `                                <el-col v-if="lr_formLookAuth('${component.prop}')" :span="${component.span}" >`
      );
      TEMPLATE.add(`                                    <el-form-item  labelWidth="0px">`);
      TEMPLATE.add(`                                        <el-button
                                             size="${component.size}" 
                                             :plain="${component.plain}"
                                             :round="${component.round}" 
                                             :circle="${component.circle}" 
                                             icon="${component.myIcon}" 
                                             type="${component.myType}"

                                             :disabled="!lr_formEditAuth('${component.prop}')"
            
                                             >${component.label}</el-button>`);
      TEMPLATE.add(`                                    </el-form-item>`);
      TEMPLATE.add(`                                </el-col>`);
    } else if (["viewtable"].includes(component.type)) {
      TEMPLATE.add(`                                <el-col v-if="lr_formLookAuth('${component.prop}')"  :span="24" >`);
      if (!window.$validatenull(component.label)) {
        TEMPLATE.add(`                                    <div class="l-title" >{{$t('${component.label}')}}</div>`);
      }
      TEMPLATE.add(`                                    <l-view-table`);

      let paramFiled = `${window.$lowerFirst(components[component.paramFiled].table)}_${window.$lowerFirst(
        components[component.paramFiled].field
      )}`;
      TEMPLATE.add(`                                    dataType="${component.dataType}"`);
      TEMPLATE.add(`                                    :isPage="${component.isPage}"`);
      TEMPLATE.add(`                                    apiCode="${component.apiCode}"`);
      TEMPLATE.add(`                                    :paramFiled="formData.${paramFiled}"`);
      TEMPLATE.add(
        `                                    :columns="${JSON.stringify(component.columns).replace(/"/g, "'")}"`
      );
      TEMPLATE.add(`                                    code="${component.dataCode}"`);
      TEMPLATE.add(`                                    />`);

      TEMPLATE.add(`                                </el-col>`);
    } else if (["card"].includes(component.type)) {
      TEMPLATE.add(`                                <el-col :span="24" v-if="lr_formLookAuth('${component.prop}')"  >`);
      TEMPLATE.add(
        `                                <el-card header="${component.label}" shadow="${component.shadow}" >`
      );
      renderForm(
        component.children,
        tableMap,
        //dataItemMap,
        //dataSourceMap,
        dbTable,

        upCtrls,
        components,
        TEMPLATE,
        DATACOMPUTED,
        FORMDATA,
        TABLEDATA,
        TABLEMETHODS,
        RULES,
        RESETFORM,
        VALIDATEFORM,
        SETFORM,
        GETFORM
      );
      TEMPLATE.add(`                                </el-card>`);
      TEMPLATE.add(`                                </el-col>`);
    } else {
      let formProp = `${window.$lowerFirst(component.table)}_${window.$lowerFirst(component.field)}`;
      if (component.display) {
        TEMPLATE.add(
          `                                <el-col v-if="lr_formLookAuth('${formProp}')" :span="${component.span}" >`
        );
      } else {
        TEMPLATE.add(
          `                                <el-col v-show="${component.display}" :span="${component.span}" >`
        );
      }

      TEMPLATE.add(`                                    <el-form-item `);
      TEMPLATE.add(`                                        label="${component.label}" `);
      TEMPLATE.add(`                                        prop="${formProp}"`);

      if (component.labelWidth) {
        TEMPLATE.add(`                                        labelWidth="${component.labelWidth}px"`);
      }
      TEMPLATE.add(`                                        > `);
      TEMPLATE.add(
        getFormComponents(component, formProp, "                                        ", upCtrls[component.prop])
      );

      TEMPLATE.add(`                                    </el-form-item>`);
      TEMPLATE.add(`                                </el-col>`);

      if (["radio", "checkbox", "select", "selectMultiple", "treeselect", "layerselect"].includes(component.type)) {
        DATACOMPUTED.add(`        ${formProp}Options(){`);
        switch (component.dataType) {
          case "1":
            // 1.静态数据
            DATACOMPUTED.add(`            return ${JSON.stringify(component.options)}`);
            break;
          case "2":
            // 2.数据字典数据
            //dataItemMap[component.dataCode] = true
            DATACOMPUTED.add(`            this.lr_loadDataItem('${component.dataCode}')`);
            if (component.type == "treeselect") {
              DATACOMPUTED.add(`            return this.lr_dataItemTree(this.lr_dataItem['${component.dataCode}'])`);
            } else {
              DATACOMPUTED.add(`            return this.lr_dataItemOptions(this.lr_dataItem['${component.dataCode}'])`);
            }
            break;
          case "3":
            // 3.数据源数据
            //dataSourceMap[component.dataCode] = true;
            //DATACOMPUTED.add(`            this.lr_loadDataSourceData('${component.dataCode}')`)
            if (component.upCtrl) {
              let upCtrlProp = `${window.$lowerFirst(components[component.upCtrl].table)}_${window.$lowerFirst(
                components[component.upCtrl].field
              )}`;
              DATACOMPUTED.add(
                `            const data = this.lr_DataSource('${component.dataCode}',true,this.formData.${upCtrlProp},'${component.dataValueKey}')`
              );
            } else {
              DATACOMPUTED.add(`            const data = this.lr_DataSource('${component.dataCode}')`);
            }

            if (component.type == "treeselect") {
              DATACOMPUTED.add(
                `            return this.lr_DataSourceTree(data,'${component.dataIdKey}','${component.dataPIdKey}','${component.dataValueKey}','${component.dataLabelKey}')`
              );
            } else {
              DATACOMPUTED.add(
                `            return this.lr_DataSourceOptions(data,'${component.dataValueKey}','${component.dataLabelKey}')`
              );
            }

            break;
        }
        DATACOMPUTED.add(`        },`);
      }

      if (["rate", "slider"].includes(component.type)) {
        FORMDATA.add(`                ${formProp}:${component.default || 0}, // ${component.label}`);
      } else if (["switch"].includes(component.type)) {
        switch (component.csType) {
          case "int":
            if (window.$validatenull(component.default)) {
              FORMDATA.add(`                ${formProp}:null, // ${component.label}`);
            } else {
              FORMDATA.add(`                ${formProp}:${Number(component.default)}, // ${component.label}`);
            }
            break;
          case "bool":
            FORMDATA.add(`                ${formProp}:${component.default == "true"}, // ${component.label}`);
            break;
          default:
            FORMDATA.add(`                ${formProp}:${component.default || ""}, // ${component.label}`);
            break;
        }
      } else {
        FORMDATA.add(`                ${formProp}:"${component.default || ""}", // ${component.label}`);
      }

      if (dbTable.length != 1) {
        const table = dbTable.find((t) => t.name == component.table);
        if (!tableMap[component.table]) {
          GETFORM.add(
            `            formData.${window.$lowerFirst(
              table.name
            )} = this.$getFormData(this.formData,'${window.$lowerFirst(component.table)}')`
          );
          SETFORM.add(
            `            this.$setFormData(this.formData,data.${window.$lowerFirst(table.name)},'${window.$lowerFirst(
              component.table
            )}')`
          );
        }
        tableMap[component.table] = true;

        //GETFORM.add(`            formData.${window.$lowerFirst(table.className)}Entity.${window.$lowerFirst(component.field)} = this.formData.${formProp} // ${component.label}`)
      }
      if (component.patterns && component.patterns.length > 0) {
        RULES.add(`                ${formProp}:[`);
        if (component.required) {
          RULES.add(`                    { required: true, message: '请输入${component.label}' },`);
        }

        component.patterns.forEach((pattern) => {
          RULES.add(`                    { pattern: ${pattern.reg}, message: '${pattern.msg}' },`);
        });

        RULES.add(`                ],`);
      } else if (component.required) {
        RULES.add(`                ${formProp}:[`);
        if (["input", "textarea", "texteditor", "number", "password"].includes(component.type)) {
          RULES.add(`                    { required: true, message: '请输入${component.label}' },`);
        } else if (["upload", "uploadimg"].includes(component.type)) {
          RULES.add(`                    { required: true, message: '请上传${component.label}' },`);
        } else {
          RULES.add(`                    { required: true, message: '请选择${component.label}' },`);
        }

        RULES.add(`                ],`);
      }
    }
  });
}

export const generatorForm = (setting, temp) => {
  let strCode = temp;
  temp = null;

  const { formInfo, dbTable, db } = setting;

  // 获取主表信息
  const mainTable = dbTable.find((t) => t.type == "main");

  const apiGet = db.find((item) => item.apiType === 1);
  const apiPut = db.find((item) => item.apiType === 3);
  const apiPost = db.find((item) => item.apiType === 2);
  let ONLYTABS = "";
  if (formInfo.tabList.length <= 1) {
    ONLYTABS = "only-tabs";
  }

  strCode = strCode.replace(new RegExp(`\\$\\$ONLYTABS,?`, "g"), ONLYTABS);

  strCode = strCode.replace(new RegExp(`\\$\\$FORMSIZE,?`, "g"), formInfo.size);
  strCode = strCode.replace(new RegExp(`\\$\\$FORMLABELPOSITION,?`, "g"), formInfo.labelPosition);
  strCode = strCode.replace(new RegExp(`\\$\\$FORMLABELWIDTH,?`, "g"), formInfo.labelWidth || 80);
  strCode = strCode.replace(new RegExp(`\\$\\$MODULECODE,?`, "g"), `${setting.moduleId}_${setting.name}`);

  strCode = strCode.replace(
    new RegExp(`\\$\\$APIGET,?`, "g"),
    `this.$http.request({url:"${apiGet.f_Url}/"+keyValue,method:"${apiGet.f_RequestMethod}" })`
  );
  strCode = strCode.replace(
    new RegExp(`\\$\\$APIPUT,?`, "g"),
    `this.$http.request({url:"${apiPut.f_Url}/"+keyValue,method:"${apiPut.f_RequestMethod}",data:postData })`
  );
  strCode = strCode.replace(
    new RegExp(`\\$\\$APIPOST,?`, "g"),
    `this.$http.request({url:"${apiPost.f_Url}",method:"${apiPost.f_RequestMethod}",data:postData, })`
  );

  // 需要导入的包
  let IMPORT = new myString();
  IMPORT.add(`    const api = window.$api.${setting.moduleId.toLowerCase()}.${window.$lowerFirst(setting.name)}`);
  strCode = IMPORT.writeTo(strCode, "IMPORT");
  IMPORT = null;

  let TEMPLATE = new myString();
  let DATACOMPUTED = new myString();
  let FORMDATA = new myString();
  let TABLEDATA = new myString();
  let TABLEMETHODS = new myString();
  let RULES = new myString();
  let RESETFORM = new myString();
  let VALIDATEFORM = new myString();
  let SETFORM = new myString();
  let GETFORM = new myString();

  let CHANGEMETHODS = new myString();

  //let dataItemMap = {}
  //let dataSourceMap = {}
  let tableMap = {};
  let upCtrls = {};
  let components = {};

  if (dbTable.length != 1) {
    GETFORM.add(`            const formData = {}`);
  }

  // 设置组件之间的级联属性
  formInfo.tabList &&
    formInfo.tabList.forEach((tab) => {
      tab.components.forEach((component) => {
        if (!["viewtable", "card", "btn"].includes(component.type)) {
          if (["gridtable"].includes(component.type)) {
            component.children.forEach((col) => {
              components[col.prop] = col;
              if (col.upCtrl) {
                upCtrls[col.upCtrl] = upCtrls[col.upCtrl] || [];
                upCtrls[col.upCtrl].push(col);
              }
            });
          } else {
            components[component.prop] = component;
            if (component.upCtrl) {
              upCtrls[component.upCtrl] = upCtrls[component.upCtrl] || [];
              upCtrls[component.upCtrl].push(component);
            }
          }
        }
      });
    });

  const tabList = getShowTabs(formInfo.tabList);

  tabList.forEach((tab, index) => {
    TEMPLATE.add(
      `                    <el-tab-pane class="l-tabs-container" :label="$t('${tab.text}')" name="tab${index}">`
    );
    TEMPLATE.add(`                        <el-row :gutter="${formInfo.gutter}">`);
    TEMPLATE.add(`                            <div class="l-rblock">`);

    renderForm(
      tab.components,
      tableMap,
      //dataItemMap,
      //dataSourceMap,
      dbTable,
      upCtrls,
      components,
      TEMPLATE,
      DATACOMPUTED,
      FORMDATA,
      TABLEDATA,
      TABLEMETHODS,
      RULES,
      RESETFORM,
      VALIDATEFORM,
      SETFORM,
      GETFORM
    );

    TEMPLATE.add(`                            </div>`);
    TEMPLATE.add(`                        </el-row>`);
    TEMPLATE.add(`                    </el-tab-pane>`);
  });

  if (dbTable.length == 1) {
    GETFORM.add(`            return this.$getFormData(this.formData,'${window.$lowerFirst(mainTable.name)}')`);
    SETFORM.add(`            this.$setFormData(this.formData,data,'${window.$lowerFirst(mainTable.name)}')`);

    //SETFORM.add(`            this.formData = data `)
    //GETFORM.add(`            return this.$deepClone(this.formData)`)
  } else {
    GETFORM.add(`            return formData`);
  }

  strCode = TEMPLATE.writeTo(strCode, "TEMPLATE");
  TEMPLATE = null;

  strCode = DATACOMPUTED.writeTo(strCode, "DATACOMPUTED");
  DATACOMPUTED = null;

  strCode = FORMDATA.writeTo(strCode, "FORMDATA");
  FORMDATA = null;

  strCode = TABLEDATA.writeTo(strCode, "TABLEDATA");
  TABLEDATA = null;

  strCode = TABLEMETHODS.writeTo(strCode, "TABLEMETHODS");
  TABLEMETHODS = null;

  strCode = RULES.writeTo(strCode, "RULES");
  RULES = null;

  strCode = RESETFORM.writeTo(strCode, "RESETFORM");
  RESETFORM = null;

  strCode = VALIDATEFORM.writeTo(strCode, "VALIDATEFORM");
  VALIDATEFORM = null;

  strCode = SETFORM.writeTo(strCode, "SETFORM");
  SETFORM = null;

  strCode = GETFORM.writeTo(strCode, "GETFORM");
  GETFORM = null;

  for (let key in upCtrls) {
    const component = components[key];
    let formProp = `${window.$lowerFirst(component.table)}_${window.$lowerFirst(component.field)}`;
    if (component.subfield) {
      CHANGEMETHODS.add(`        ${formProp}_change(row){`);
    } else {
      CHANGEMETHODS.add(`        ${formProp}_change(){`);
    }

    upCtrls[key].forEach((child) => {
      if (child.subfield) {
        CHANGEMETHODS.add(`            this.$set(row,'${window.$lowerFirst(child.field)}',undefined)`);
      } else {
        let formProp2 = `${window.$lowerFirst(child.table)}_${window.$lowerFirst(child.field)}`;
        CHANGEMETHODS.add(`            this.$set(this.formData,'${formProp2}',undefined)`);
      }
    });
    CHANGEMETHODS.add(`        },`);
  }

  strCode = CHANGEMETHODS.writeTo(strCode, "CHANGEMETHODS");
  CHANGEMETHODS = null;

  // 给主键赋值，流程中用到，需要主键为guid的

  // 获取主表主键
  const mainKey = mainTable.columns.find((t) => t.isPrimary);
  let EDITFORM = new myString();

  EDITFORM.add(
    `                delete postData.${window.$lowerFirst(mainTable.name)}.${window.$lowerFirst(mainKey.name)}`
  );
  strCode = EDITFORM.writeTo(strCode, "EDITFORM");
  EDITFORM = null;

  let SAVEFORM = new myString();

  if (mainKey && mainKey.csType == "string") {
    if (dbTable.length == 1) {
      SAVEFORM.add(`                postData.${window.$lowerFirst(mainKey.name)} = keyValue`);
    } else {
      SAVEFORM.add(
        `                postData.${window.$lowerFirst(mainTable.name)}.${window.$lowerFirst(mainKey.name)} = keyValue`
      );
    }
  } else {
    SAVEFORM.add(`                // 主键不为字串类型，如果要作为流程表单请手动绑定流程关联字段`);

    SAVEFORM.add(`               if(keyValue){ 
                postData.${window.$lowerFirst(mainTable.name)}.${window.$lowerFirst(mainKey.name)} = keyValue 
                  }`);
  }
  strCode = SAVEFORM.writeTo(strCode, "SAVEFORM");
  SAVEFORM = null;

  return strCode;
};
